const connections = require('../app/database');

class UserService {

    //注册用户 用户名 密码 名称
    async create(user) {
        const { username, password } = user;
        const statement = `INSERT INTO users (username, password, name) VALUES (?, ?, ?);`;
        
        try {
            const result = await connections.execute(statement, [username, password, username]);
            return result[0];
        } catch(e) {
            console.log("创建用户失败", e);
        }
    }

    //创建用户信息
    async createUserInformation(userInfo) {
        const { name, id } = userInfo;
        const statement = `INSERT INTO user_information (name, userId, roleId, roleName) VALUES (?, ?, ?, ?);`;

        const result = await connections.execute(statement, [name, id, 2, '登录用户']);

        return result[0];
    }

    //查询用户 获取账号密码
    async getUserByName(username) {

        const statement =  `SELECT * FROM users WHERE username = ?;`;

        try {
            const result = await connections.execute(statement, [username]);
            return result[0];
        } catch(e) {
            console.log("查询用户失败", e);
        }
    }

    //获取用户详细
    async getUserInformationById(userId) {
        const statement = `SELECT * FROM user_information WHERE userId = ?`;

        try {
            const result = await connections.execute(statement, [userId]);
            return result[0];
        } catch(e) {
            console.log("查询用户失败", e);
        }
    }

}

module.exports = new UserService();